import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.text.DecimalFormat;
import java.io.IOException;
import javax.imageio.ImageIO;
import java.sql.Timestamp;
public class BusUI extends JFrame {
    private JTextField startField, endField, balanceField; 
    private JTextArea resultArea;
    private JLabel startLabel, endLabel, balanceLabel;
    private JButton confirmButton, buyButton, exitButton;
    public BusUI() {
        initializeUI();
    }

    private void initializeUI() {
        setTitle("公交售票系统(模拟购票)");
        setSize(800, 600);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setLayout(new BorderLayout(5, 5));

        JPanel inputPanel = new JPanel(new FlowLayout(FlowLayout.LEFT));
        setupLabelsAndFields(inputPanel);

        confirmButton = new JButton("确定");
        confirmButton.addActionListener(this::confirmInput);
        inputPanel.add(confirmButton);

        add(inputPanel, BorderLayout.NORTH);

        resultArea = new JTextArea(5, 30);
        resultArea.setEditable(false);
        JScrollPane resultScrollPane = new JScrollPane(resultArea);
        add(resultScrollPane, BorderLayout.CENTER); // 将结果区域放在中间

        JPanel buttonPanel = new JPanel(new FlowLayout(FlowLayout.LEFT));
        buyButton = new JButton("购票");
        buyButton.addActionListener(this::handleBuyTicket);
        buttonPanel.add(buyButton);
        buyButton.setVisible(false);
       exitButton = new JButton("退出");
       //exitButton.addActionListener(e -> System.exit(0));
       exitButton.addActionListener(e -> {
    // 在控制台输出信息
    System.out.println("购票记录已成功保存！");
    
    // 退出系统
    System.exit(0);
    });
        buttonPanel.add(exitButton);
        add(buttonPanel, BorderLayout.SOUTH);
    }

    private void setupLabelsAndFields(JPanel inputPanel) {
        startLabel = new JLabel("始发站:");
        startField = new JTextField(5);
        endLabel = new JLabel("目的站:");
        endField = new JTextField(5);
        balanceLabel = new JLabel("公交卡余额:");
        balanceField = new JTextField(5);
        inputPanel.add(startLabel);
        inputPanel.add(startField);
        inputPanel.add(endLabel);
        inputPanel.add(endField);
        inputPanel.add(balanceLabel);
        inputPanel.add(balanceField);
    }

    private void confirmInput(ActionEvent e) {
        if (validateInput()) {
            buyButton.setVisible(true);
            confirmButton.setVisible(false);
        }
    }

    private boolean validateInput() {
        String start = startField.getText();
        String end = endField.getText();
        String balanceText = balanceField.getText();
        if (start.isEmpty() || end.isEmpty() || balanceText.isEmpty()) {
            JOptionPane.showMessageDialog(this, "请填写所有字段。", "输入错误", JOptionPane.WARNING_MESSAGE);
            return false;
        }
        try {
            double balance = Double.parseDouble(balanceText);
            if (balance < 0) {
                JOptionPane.showMessageDialog(this, "卡内余额不能为负数。", "输入错误", JOptionPane.WARNING_MESSAGE);
                return false;
            }
            resultArea.append("输入验证成功。\n");
            return true;
        } catch (NumberFormatException ex) {
            JOptionPane.showMessageDialog(this, "卡内余额输入不正确，请输入数字。", "输入错误", JOptionPane.WARNING_MESSAGE);
            return false;
        }
    }

    private void saveTicketRecord(String paymentMethod, boolean isSuccess, double amount) {
    String start = startField.getText();
    String end = endField.getText();
    
    TicketRecord record = new TicketRecord(
        paymentMethod,
        isSuccess,
        amount,
        start,
        end
    );
    
    // 在后台线程保存记录
    new Thread(() -> DBUtil.saveTicketRecord(record)).start();
    }

    private void handleBuyTicket(ActionEvent e) {
        String start = startField.getText();
        String end = endField.getText();

        if (!isStationValid(start) || !isStationValid(end)) {
            JOptionPane.showMessageDialog(this, "该站台无路线。", "站点错误", JOptionPane.WARNING_MESSAGE);
            return;
        }
        double amount = calculateFare(start, end);
        int option = JOptionPane.showOptionDialog(this,
                "票价为：" + new DecimalFormat("#.##").format(amount) + "元\n选择支付方式：",
                "购票",
                JOptionPane.YES_NO_OPTION,
                JOptionPane.QUESTION_MESSAGE,
                null,
                new Object[]{"公交卡支付", "微信支付"},
                null);

        if (option == 0) {
        boolean success = handleCardPayment(amount);
        // 失败时已记录，成功时在handleCardPayment中记录
    } else if (option == 1) {
        handleWeChatPayment(amount); // 微信支付总是成功
    }
    }
    private void handleWeChatPayment(double amount) {
    resultArea.append("购票成功，使用微信支付。\n");
    saveTicketRecord("微信", true, amount);
}
    private boolean isStationValid(String station) {
        try {
            int stationNumber = Integer.parseInt(station);
            return stationNumber >= 1 && stationNumber <= 4;
        } catch (NumberFormatException e) {
            return false;
        }
    }
    private boolean handleCardPayment(double amount) {
    try {
        double balance = Double.parseDouble(balanceField.getText());
        if (balance >= amount) {
            balance -= amount;
            balanceField.setText(String.format("%.2f", balance));
            resultArea.append("购票成功，使用公交卡支付。\n");
            resultArea.append("剩余余额: " + new DecimalFormat("#.##").format(balance) + "元\n");
            
            // 保存购票记录
            saveTicketRecord("公交卡", true, amount);
            return true;
        } else {
            JOptionPane.showMessageDialog(this, "公交卡余额不足。", "支付错误", JOptionPane.WARNING_MESSAGE);
            saveTicketRecord("公交卡", false, amount);
            return false;
        }
    } catch (NumberFormatException e) {
        JOptionPane.showMessageDialog(this, "卡内余额输入不正确，请输入数字。", "输入错误", JOptionPane.WARNING_MESSAGE);
        return false;
    }
}
    private double calculateFare(String start, String end) {
        int startStation = Integer.parseInt(start);
        int endStation = Integer.parseInt(end);
        int distance = Math.abs(startStation - endStation);
        return distance * 5;
    }
    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> new BusUI().setVisible(true));
    }
}
